package mymvc.ui
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.ui.Keyboard;
	import flash.ui.Mouse;

	/**
	 * 关注前台使用的一些对象的基本行为，比如移动中心点 ,上下左右键控制物体的移动
	 */
	public class BaseBehaviour
	{
		public function BaseBehaviour()
		{
		}
		
		public static function moveCenterPoint(target:DisplayObject,centerX:int,centerY:int):void{
			if(target == null){
				throw new Error("源目标为空");
				return ;
			}
			target.x = centerX - target.width / 2;
			target.y = centerY - target.height / 2;
		}
		
		public static function moveByKey(target:DisplayObject):void{
			var vx:int = 0;
			var vy:int = 0;
			if(target.parent == null){
				throw(new Error("这已经是主Sprite了"));
			}
			var parent:DisplayObject = target.parent;
			parent.stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
			parent.stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
			parent.stage.addEventListener(Event.ENTER_FRAME,onEnterFrame);
			function onKeyDown(event:KeyboardEvent):void{
				//trace("move fighter");
				if(event.keyCode == Keyboard.LEFT){
					vx = -3;	
				}else if(event.keyCode == Keyboard.RIGHT){
					vx = 3;
				}else if(event.keyCode == Keyboard.UP){
					vy = -3;
				}else if(event.keyCode == Keyboard.DOWN){
					vy = 3;
				}
					
				
			}
			
			function onKeyUp(event:KeyboardEvent):void{
				if(event.keyCode == Keyboard.LEFT){
					vx = 0;	
				}else if(event.keyCode == Keyboard.RIGHT){
					vx = 0;
				}else if(event.keyCode == Keyboard.UP){
					vy = 0;
				}else if(event.keyCode == Keyboard.DOWN){
					vy = 0;
				}
			}
			
			function onEnterFrame(event:Event):void{
				target.x += vx;
				target.y += vy;
				//控制边界问题。。。
				if((target.x + target.width)>=parent.stage.stageWidth){
					vx = 0;
					target.x = parent.stage.stageWidth - target.width;
				}else if(target.x<=0){
					vx = 0;
					target.x = 0;
				}else if((target.y + target.height)>parent.stage.stageHeight){
					vy = 0;
					target.y = parent.stage.stageHeight - target.height;
				}else if(target.y <= 0){
					vy = 0;
					target.y = 0;
				}
				
			}
		}
		
		public static function moveByMouse(target:DisplayObject):void{
			target.parent.addEventListener(Event.ENTER_FRAME,onEnterFrame);
			function onEnterFrame(event:Event):void{
				
				moveCenterPoint(target,target.parent.stage.mouseX,
					target.parent.stage.mouseY);
				var parent:DisplayObject = target.parent;
				//控制边界问题。。。
				if((target.x + target.width)>=parent.stage.stageWidth){
					target.x = parent.stage.stageWidth - target.width;
				}else if(target.x<=0){
					target.x = 0;
				}else if((target.y + target.height)>parent.stage.stageHeight){
					target.y = parent.stage.stageHeight - target.height;
				}else if(target.y <= 0){
					target.y = 0;
				}
			}
		}
	}
}